package ${package.Controller};

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
<#if codeStyle == "kys" || codeStyle == "ca">
import ${resultPackageValue}.IzhResponseBody;
import ${resultPackageValue}.ResponseUtil;
</#if>
<#if codeStyle == "common" || codeStyle == "dms">
import ${resultPackageValue}.Result;
</#if>
import org.springframework.web.bind.annotation.RestController;
<#if swagger2>
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
</#if>
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.nio.charset.StandardCharsets;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import ${voPackageValue}.${voName};
import ${pagePackageValue}.${pageName};
import ${formPackageValue}.${formName};
import ${package.Service}.${table.serviceName};
import java.time.LocalDateTime;

/**
 * @Description: ${table.comment!}
 * @Author: ${author}
 * @CreateDate: ${date}
 * @Version: 1.0.0
 * @Company: ${company}
 * @menu ${table.comment!}接口
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/${pathName}" )
<#if swagger2>
@Tag(name = "${table.comment!}管理")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
</#if>
@Slf4j
public class ${table.controllerName} {

    private final ${className}Service ${classname}Service;

    /**
    * 分页查询
    * @param page 分页对象
    * @return
    */
    <#if swagger2>
    @Operation(summary = "分页查询", description = "分页查询")
    </#if>
    @GetMapping("/page")
    <#if codeStyle == "kys" || codeStyle == "ca">
    public IzhResponseBody<Page<${voName}>> get${className}Page(${pageName} page) {
        return ResponseUtil.success(${classname}Service.getPage(page));
    </#if>
    <#if codeStyle == "common" || codeStyle == "dms">
    public Result<Page<${voName}>> get${className}Page(${pageName} page) {
        return Result.ok(${classname}Service.getPage(page));
    </#if>
    }


    /**
    * 通过id查询${table.comment}
    * @return Result
    */
    <#if swagger2>
    @Operation(summary = "通过id查询", description = "通过id查询")
    </#if>
    @GetMapping("/{id}")
    <#if codeStyle == "kys" || codeStyle == "ca">
    public IzhResponseBody<${voName}> getById(@PathVariable("id" ) Integer id) {
        return ResponseUtil.success(${classname}Service.getDetail(id));
    </#if>
    <#if codeStyle == "common" || codeStyle == "dms">
    public Result<${voName}> getById(@PathVariable("id" ) Integer id) {
        return Result.ok(${classname}Service.getDetail(id));
    </#if>
    }

    /**
    * 新增${table.comment}
    * @param form ${table.comment}
    * @return Result
    */
    <#if swagger2>
    @Operation(summary = "新增${table.comment}", description = "新增${table.comment}")
    </#if>
    @PostMapping
    <#if codeStyle == "kys" || codeStyle == "ca">
    public IzhResponseBody save(@RequestBody ${formName} form) {
        ${classname}Service.addEntity(form);
        return ResponseUtil.ok();
    </#if>
    <#if codeStyle == "common" || codeStyle == "dms">
    public Result save(@RequestBody ${formName} form) {
        return Result.ok(${classname}Service.addEntity(form));
    </#if>
    }

    /**
    * 修改${table.comment}
    * @param form ${table.comment}
    * @return Result
    */
    <#if swagger2>
    @Operation(summary = "修改${table.comment}", description = "修改${table.comment}")
    </#if>
    @PutMapping
    <#if codeStyle == "kys" || codeStyle == "ca">
    public IzhResponseBody updateById(@RequestBody ${formName} form) {
        return ResponseUtil.ok();
    </#if>
    <#if codeStyle == "common" || codeStyle == "dms">
    public Result updateById(@RequestBody ${formName} form) {
        return Result.ok(${classname}Service.editEntity(form));
    </#if>
    }

    /**
    * 通过id删除${table.comment}
    * @param id
    * @return Result
    */
    <#if swagger2>
    @Operation(summary = "通过id删除${table.comment}", description = "通过id删除${table.comment}")
    </#if>
    @DeleteMapping("/{id}" )
    <#if codeStyle == "kys" || codeStyle == "ca">
    public IzhResponseBody removeById(@PathVariable Integer id) {
        return ResponseUtil.ok();
    </#if>
    <#if codeStyle == "common" || codeStyle == "dms">
    public Result removeById(@PathVariable Integer id) {
        return Result.ok(${classname}Service.removeById(id));
    </#if>
    }

    <#if needImportExport>
    /**
    * 导入EXCEL
    * @param file excel模板文件
    * @return Result
    */
    @PostMapping("import-excel")
    <#if codeStyle == "kys" || codeStyle == "ca">
    public IzhResponseBody importExcel(@RequestParam("file") MultipartFile file){
        if (file.isEmpty()) {
            return ResponseUtil.error("操作失败,文件不存在!");
        }
        String originalFilename = file.getOriginalFilename();
        if (!StrUtil.endWithAny(originalFilename, ".xlsx", ".xls")) {
            return ResponseUtil.error("操作失败,文件类型不合法!");
        }
        boolean result=${classname}Service.importExcel(file);
        if(!result){
            return ResponseUtil.error("导入失败，请检查文件或联系管理员");
        }
        return ResponseUtil.ok();
    </#if>
    <#if codeStyle == "common" || codeStyle == "dms">
    public Result importExcel(@RequestParam("file") MultipartFile file){
        if (file.isEmpty()) {
            return Result.failed().setMessage("操作失败,文件不存在!");
        }
        String originalFilename = file.getOriginalFilename();
        if (!StrUtil.endWithAny(originalFilename, ".xlsx", ".xls")) {
            return Result.failed().setMessage("操作失败,文件类型不合法!");
        }
        boolean result=${classname}Service.importExcel(file);
        if(!result){
            return Result.failed().setMessage("导入失败，请检查文件或联系管理员");
        }
        return Result.ok();
    </#if>
    }

    /**
    * 导出EXCEL
    * @param page
    * @return
    */
    @GetMapping("/export-excel")
    public ResponseEntity<byte[]> exportExcel(${pageName} page) {
        try {
            byte[] excelBytes = ${classname}Service.exportExcel(page);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            // 对中文文件名进行编码
            String encodedFileName = new String(String.format("${table.comment!}(%s).xlsx", DateUtil.format(LocalDateTime.now(), DatePattern.NORM_DATE_PATTERN)).getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
            headers.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + encodedFileName);
            return ResponseEntity.ok().headers(headers).body(excelBytes);
        } catch (Exception e) {
            log.error("导出EXCEL文件异常",e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
    </#if>
}